/*********************************************************
          File Name:8.10.cpp
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Mon 14 Sep 2015 11:11:07 AM CST
**********************************************************/

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>

using std::string; using std::vector; using std::ifstream; using std::istringstream;

void getbuf(const string &file, vector<string> &v)
{
        ifstream ifs(file);
        string line;

        if(ifs)
        {
                while(std::getline(ifs, line))
                {
                        v.push_back(line);
                }
                ifs.close();
        }
        else
                std::cerr << "can't open file for read\n";
}

void getword(vector<string> &v, vector<string> &word)
{
        string tmp;
        istringstream is;

        for(auto &line: v)      // `&` faster than copy
        {
                is.str(line);
                while(is >> tmp)
                        word.push_back(tmp);
                is.clear();
        }
}

int main(int argc, char *argv[])
{
        if(argc != 2)
        {
                std::cerr << argv[0] << " filename\n"
                        "file must exists and has contents" << std::endl;
                exit(1);
        }

        vector<string> v;
        vector<string> word;

        getbuf(argv[1], v);
        getword(v, word);

        std::cout << std::unitbuf;      // no buffer

        for(auto &w: word)
        {
                std::cout << w << std::endl;
        }

        return 0;
}
